'use strict';

zmvp
    .factory('Auth', function($rootScope, $state, $q,localStorageService,$cookieStore, $resource,AuthServerProvider,Account,Register) {
        var _user=$cookieStore.get('user');
        var setUser=function (user) {
            _user=user;
            $cookieStore.put('user',_user);
        }
        return {
            setUser:setUser,
            isAuthorized:function(){
                return true;
            },
            isLoggedIn:function(){
                return _user?true:false;
            },
            hasAccount:function(){
                var q=$q.defer();
                var pm=q.promise;
                if (!_user)
                    Account.get(function(data){
                        setUser(data);
                        q.resolve(data);
                    },function(){
                        q.resolve();
                    });
                else{
                    q.resolve();
                }
                return pm;
            },
            getUser:function () {
                return _user;
            },
            getId:function () {
                return _user?_user.id:null;
            },
            getToken:function () {
                return _user?_user.token:"";
            },
            logout:function(){
                AuthServerProvider.logout().then(function(){
                    $cookieStore.remove('user');
                    _user=null;
                    $state.go("login");
                });
            },
            login:function(credentials){
                var q=$q.defer();
                var promise=q.promise;
                AuthServerProvider.login(credentials).then(function (data) {
                    Account.get(function(data){
                        setUser(data);
                        q.resolve();
                    },function(){
                        q.reject();
                    });
                });
                return promise;
            },
            createAccount: function (account) {
                var q=$q.defer();
                Register.save(account,
                    function () {
                        q.resolve()
                    },
                    function (err) {
                        q.reject()
                    });
                return q.promise;
            }
        }
    });
